/**
 * 定时任务，推送通知
 */
import schedule from "node-schedule";
import { createNotification, logger, getUuid, getCurrentTime } from "#/utils";
import { Task } from "#/types";
import jobLogService from "./log";
import jobService from "./index";
import jobDao from "#/dao/job";

const [notification] = createNotification();

function create(job: Task, next = () => {}, log = true) {
  //该任务可能已经存在，会有多次创建的可能，所以先取消掉已有的
  schedule.cancelJob(job.id);
  schedule.scheduleJob(job.id, job.cron_expression, async () => {
    if (job.push_status == 1) {
      notification(job.push_content);
    }
    next();
  });

  if (log) {
    jobLogService.insert({
      id: getUuid(),
      task_id: job.id,
      task_name: job.name,
      create_time: getCurrentTime(),
      status: 2,
      error_message: "",
      result: "创建成功",
    });
  }
  logger(`📌 已启用定时任务: ${job.name} (${job.cron_expression})`);
}

async function cancel(jobId) {
  const [task] = await jobDao.queryById(jobId);
  logger(task);
  const now = new Date();
  logger(`[${now.toLocaleString()}] 🚀 暂停任务: ${task.name}`);
  jobLogService.insert({
    id: getUuid(),
    task_id: task.id,
    task_name: task.name,
    create_time: getCurrentTime(),
    status: 2,
    error_message: "",
    result: "暂停成功",
  });
  schedule.cancelJob(jobId); // 使用创建时指定的ID
}

async function cancelAll() {
  const tasks = await jobService.queryAll();
  tasks.map((task: Task) => {
    schedule.cancelJob(task.id);
    const now = new Date();
    logger(`[${now.toLocaleString()}] 🚀 暂停任务: ${task.name}`);
    jobLogService.insert({
      id: getUuid(),
      task_id: task.id,
      task_name: task.name,
      create_time: getCurrentTime(),
      status: 2,
      error_message: "",
      result: "暂停成功",
    });
  });
}

async function restoreAll() {
  const tasks = await jobService.queryAll();
  tasks.map((task: Task) => {
    create(
      task,
      () => {
        const now = new Date();
        logger(`[${now.toLocaleString()}] 🚀 执行任务: ${task.name}`);
        const result = task.push_status ? "执行成功,已推送" : "执行成功,未推送";
        jobLogService.insert({
          id: getUuid(),
          task_id: task.id,
          task_name: task.name,
          create_time: getCurrentTime(),
          status: 1,
          error_message: "",
          result,
        });
      },
      false
    );
  });
}

async function restore(jobId) {
  const [task] = await jobDao.queryById(jobId);
  create(
    task,
    () => {
      const now = new Date();
      logger(`[${now.toLocaleString()}] 🚀 执行任务: ${task.name}`);
      const result = task.push_status ? "执行成功,已推送" : "执行成功,未推送";
      jobLogService.insert({
        id: getUuid(),
        task_id: task.id,
        task_name: task.name,
        create_time: getCurrentTime(),
        status: 1,
        error_message: "",
        result,
      });
    },
    false
  );
  jobLogService.insert({
    id: getUuid(),
    task_id: task.id,
    task_name: task.name,
    create_time: getCurrentTime(),
    status: 2,
    error_message: "",
    result: "重启成功",
  });
}

export default {
  create,
  restoreAll,
  cancel,
  cancelAll,
  restore,
};
